package com.foreknow.test;

import com.foreknow.bean.Admin;

import java.sql.*;

/**
 * 工具类
 */
public class DBUtils {
    private Connection conn;
    private PreparedStatement pstmt;
    private  ResultSet rs;
    /**
     * 连接数据库
     */
    public Connection getConnection() throws Exception {
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr_systemdb?useUnicode=true&characterEncoding=utf8","root","123456");
        return conn;
    }

    /**
     * 查询的方法
     * 参数？ String
     * 返回值类型？ ResultSet
     * SQL: select * from admin where username=? and password=?
     *
     * 作业：将此方法的返回值类型改为List
     */
    public ResultSet Query(String sql,Object...values) throws SQLException {
       pstmt =  conn.prepareStatement(sql);
       for(int i = 0;i<values.length;i++){
           //将？替换为具体的值  setString(第几个？,具体的值)
           pstmt.setObject(i+1,values[i]);
       }
        //执行查询
        rs = pstmt.executeQuery();
        return rs;
    }

    /**
     * insert delete update的方法  DML操作
     */
    public int update(String sql,Object...values) throws SQLException {
        pstmt =  conn.prepareStatement(sql);
        for(int i = 0;i<values.length;i++){
            //将？替换为具体的值  setString(第几个？,具体的值)
            pstmt.setObject(i+1,values[i]);
        }
        int isRight = pstmt.executeUpdate();
        return isRight;
    }
    /**
     * 关闭资源
     */
    public void close() throws Exception {
        if (rs!=null){
            rs.close();;
        }
        if(pstmt!=null){
            pstmt.close();
        }
        if(conn!=null){
            conn.close();
        }
    }

    public static void main(String[] args) throws Exception {
        DBUtils dbUtils = new DBUtils();
        dbUtils.getConnection();
        //查询
        //        ResultSet rs = dbUtils.Query("select * from admin where username=? and password=?","tom","123456");
        //        while (rs.next()){
        //            //获取到当前行列的值
        //            String username = rs.getString("username");
        //            String password = rs.getString("password");
        //            System.out.println(username+"------"+password);
        //        }

        //添加
               int isRigth =  dbUtils.update("insert into admin(username,password,age,school,phone) values(?,?,?,?,?)","fender","111111",30,"forknow","121212121212");
                System.out.println(isRigth);

        //删除
//        int ok =  dbUtils.update("delete from admin where id=?",2);
//        System.out.println(ok);
    }

}
